<?php

class CardAction extends CommonAction
{
	private $_description = array ('1' => '打卡成功', '-1' => '未登录', '-2' => '今日已打卡', '-3' => '数据库错误');
	
	public function index() {
		$this->display();
	}
	
	public function cardList($month){
		if(! $this->Core->User->u_id) return '';
		$_ucd = array(
					'u_id'=>$this->Core->User->u_id, 
					'ucd_date'=>array('like', $month.'%')
		);
		$card_list = M('Ucard')->where($_ucd)->select();
		return $card_list;
	}
	
	# 打卡接口
	public function onRunCard(){
		$user = getInfoById ( 'User', $this->Core->User->u_id );
		
		$_result = $this->checkLogin();
			
		if ($_result == 1)
			$_result = $this->checkRunCard($user['u_id']);
		
		if ($_result == 1)
			$_result = $this->runCard ($user);
		
		$_rdata = array ('status' => $_result, 'msg' => $this->_description [$_result] );
		die ( json_encode ( $_rdata ) );
	}
	
	# 判断是否登录
	private function checkLogin(){
		return $this->isLogin ? 1 : -1 ;
	}
	
	# 判断是否已经打卡
	private function checkRunCard($u_id){
		$_ucd['u_id'] = $u_id;
		$_ucd['ucd_date'] = date('Y-m-d', time());
		$ucd = M('Ucard')->where($_ucd)->find();
		return $ucd ? -2 : 1 ;
	}
	
	# 执行打卡
	private function runCard($user){
		$u_last_run_cardday = D('Card')->lastCardDate($user['u_id']);
		$u_run_carddays = (date('Y-m-d', strtotime('-1 days')) == $u_last_run_cardday)? $user['u_run_carddays']+1 : 1 ;
		# step.1 用户金币，打卡日期等更新
		D('User')->updateCarddays($user, $u_run_carddays);
		
		# step.2用户打卡记录
		D('Card')->addCard($user['u_id']);
		
		# step.3 用户金币增加记录
		import('@.Util.UserGolds');
		$reg_gold = ($u_run_carddays*5 > 25) ? 25 : $u_run_carddays*5 ;
		$card_params = array('reg_gold'=> $reg_gold, 'reg_description'=>date('Y-m-d').' 连续打卡 '.$u_run_carddays.'天,增加'.$reg_gold.'金币');
		$card_userGolds = new UserGolds($this->Core->User, $card_params);
		$card_userGolds->save();
		
		$this->_description['1'] = $card_params ['reg_description'];
		return 1;
	}
	

}
?>